import * as React from 'react'

// meta类型需要给add todo item的时候用, onDelete和onToggleDone需要从list中透传过来
interface IListItemMeta {
  desc?: string;
  id: number;
  isDone: boolean;
}

interface IListItem extends IListItemMeta {
  onDelete: (id: number) => void;
  onToggleDone: (id: number) => void;
  onChangeInfo: (val: string, id: number) => void;
}

interface IListItemState {
  isOpenEdit: boolean
}

class TodoItem extends React.Component<IListItem, IListItemState> {
  public static defaultProps = {
    id: 0,
    isDone: false,
    onDelete: () => null,
    onToggleDone: () => null
  }
  public state = {
    isOpenEdit: false
  }
  public render() {
    const { desc, isDone } = this.props;
    const { isOpenEdit } = this.state;
    return (
      <li className={isDone ? 'is-done' : ''}>
        <div className="todo__item--desc">
          {
            isOpenEdit
            ? (
              <input
                type="text"
                defaultValue={desc}
                onChange={this.onChangeInfo}
                onBlur={this.evtBlur}
                autoFocus={true}
              />
            )
            : <p onClick={this.onToggleDone}>{desc}</p>
          }
        </div>
        <button onClick={this.evtToggleEdit}>编辑</button>
        <button onClick={this.onDelete}>删除</button>
      </li>
    )
  }
  public onDelete = () => this.props.onDelete(this.props.id)
  public onToggleDone = () => this.props.onToggleDone(this.props.id)
  public onChangeInfo = (ev: React.ChangeEvent<HTMLInputElement>) => {
    this.props.onChangeInfo(ev.currentTarget.value, this.props.id);
  }
  private evtToggleEdit = () => this.setState({ isOpenEdit: !this.state.isOpenEdit })
  private evtBlur = () => this.setState({ isOpenEdit: false })
}

export { IListItem, IListItemMeta }
export default TodoItem